import React, {useMemo, useEffect, Fragment} from "react";
import { getDefaultPathName } from "@/utils/util";
import {getMenuData} from '@ant-design/pro-layout';
import { useAppData, useLocation, history, useModel } from "@umijs/max";
import useTabRouter from "@/hooks/useTabRouter";
import { Tabs, Dropdown } from 'antd';
import { CloseCircleOutlined } from '@ant-design/icons';
import {useComponentDidMount} from "@/hooks";
import { verifyLogin } from "@/utils/util";
import qs from 'qs';

const MAX_ROUTER_LENGTH = 7;

const PageLayout = () => {
  const appData = useAppData();
  const { routeComponents, routes: routesSetting } = appData;
  const routesList = Object.keys(routesSetting).reduce((p, v) => [...p, {...routesSetting[v], component: routeComponents[v]}], []);
  const menudata = getMenuData(routesList, { locale: true });
  const authPathname = getDefaultPathName(); // 默认跳转地址
  const defaultRoute = menudata?.breadcrumbMap?.get(authPathname);
  const isDefaultRoute = (v) => v.pathname === authPathname;
  const { refreshDict, allDicts, loading: dictLoading } = useModel('dictModel');
  const { refreshSettlementWeek, settlementWeek, loading: settlementWeekLoading } = useModel('settlementWeekModel');

  const {
    routers,
    activeKey,
    setActiveKey,
    removeRoute,
    cleanup,
    addRouters,
    overflowRouters,
  } = useTabRouter({
    defaultRoute: [
      {
        ...defaultRoute,
        title: defaultRoute?.name,
        pathname: authPathname,
        content: defaultRoute?.component,
        exact: defaultRoute?.exact,
        currentRoute: defaultRoute,
      },
    ],
    defaultActiveKey: authPathname,
    menudata,
  });
  const location = useLocation();
  const memoRouters = useMemo(() => {
    if (routers.length > MAX_ROUTER_LENGTH) {
      overflowRouters();
    }

    return routers.reduce((acc, curr) => {
      acc.push(curr);
      return acc;
    }, []);
  }, [JSON.stringify(routers)]);

  useEffect(() => {
    const hasValue = Object.keys(routesSetting).some(key => routesSetting?.[key]?.path === location.pathname);
    // 404页面单独处理，没有在useTabRouter里面处理， 即跳转404页面5S后回首页
    // 后续考虑使用Auth组件，并整合权限
    if (!hasValue) {
      history.replace('/404');
      setTimeout(() => {
        removeRoute('404');
      }, 5000)
      return;
    }
    addRouters({ ...location });
  }, [location])

  const handleRightMenuClick = (item) => {
    const { key, active } = item;
    const actionMaps = {
      currentOther: [removeRoute, active, 'pathname'],
      current: [removeRoute, activeKey, 'pathname'],
      all: [cleanup],
      other: [cleanup, [activeKey]],
    };
    const [action, ...params] = actionMaps[key];
    action.apply(null, [...params]);

    if (key === 'all') {
      // 关闭全部之后, 重定向到导航页
      history.replace(authPathname);
    }
  };
  const memoMoreOp = {
    items: [
      {
        label: '关闭',
        key: 'current'
      },
      {
        label: '关闭其他',
        key: 'other'
      },
      {
        label: '关闭全部',
        key: 'all'
      },
    ],
    onClick: handleRightMenuClick
  }
  

  const tabItems = useMemo(() => {
    return memoRouters.map((v) => {
      return {
        label: v.title,
        title: v.title,
        key: v.pathname,
        pathname: v.pathname,
        children: (
          <div style={{background: '#fff', padding: 15}}>
            {/* <Outlet /> */}
            {React.createElement(v.content, { key: v.key })}
          </div>
        )
      }
    });
  }, [JSON.stringify(memoRouters)]);

  const TabBar = (propValues) => {
    return (
      <div className="customer_tab-bar">
        {tabItems.map((item) => {
          return (
            <div
              key={item.key}
              className={`customer_tab-item ${
                propValues.activeKey === item.key ? 'checked' : ''
              }`}
            >
              {isDefaultRoute(item) ? (
                item.label
              ) : (
                <Fragment>
                  <Dropdown menu={memoMoreOp} placement="bottomLeft" trigger={['contextMenu']}>
                    <div
                      onClick={(e) => {
                        e.stopPropagation();
                        const tab = item.key;
                        if (tab === activeKey) return; // 点击当前已激活的Tab不做任何操作
                        const current = routers?.find((v) => v?.pathname === tab);
                        history.push({ pathname: current.pathname, search: current?.search });
                        setActiveKey(tab);
                      }}
                    >
                      {item.label}
                    </div>
                  </Dropdown>
                  <div
                    className="customer_tab-item-close"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRightMenuClick({ key: 'currentOther', active: item.pathname });
                    }}
                  >
                    <CloseCircleOutlined className="customer__tab-item__close-icon" />
                  </div>
                </Fragment>
              )}
            </div>
          );
        })}
      </div>
    );
  };

  const tabChange = (activeKey) => {
    history.replace(activeKey);
    setActiveKey(activeKey);
  }

  useComponentDidMount(() => {
    // 校验是否登录，没有登录则跳转登录页
    // 后续考虑整合到权限中
    if (!verifyLogin()) {
      history.push('/login');
      return;
    }
    // 获取全局的字典配置
    if (!allDicts?.length && !dictLoading) {
      refreshDict();
    }
    if (!settlementWeek?.length && !settlementWeekLoading) {
      refreshSettlementWeek();
    }
  })

  return (
    <div>
      <Tabs
        activeKey={activeKey}
        onChange={tabChange}
        items={tabItems}
        hideAdd
        size="small"
        tabBarStyle={{ marginBottom: 0, backgroundColor: '#F3F6F9' }}
        tabBarGutter={4}
        renderTabBar={(values) => {
          return <TabBar {...values} />;
        }}
       />
    </div>
  );
}
export default PageLayout;